package main

import(
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"net/url"
	"strings"
)

func main() {
	SendGet()
	SendPost()
}
func SendGet(url, params string) (string, error) {
	//发送请求
	resp, err := http.Get("http://localhost")
	if err != nil || resp.StatusCode != http.StatusOK {
		fmt.Println("错误:发送请求", err)
		return err
	}

	//接收到返回数据
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body) //此处可增加输入过滤

	if err != nil {
		fmt.Println("错误:读取body", err)
		return err
	}

	fmt.Println(string(body))

	if response.StatusCode == 200 {
		fmt.Println("ok")
	} else {
		fmt.Println("error")
	}
}

func SendPost(url, params string) (string, error) {
	//post的body内容,当前为json格式
	reqbody := `
        {
       "touser":"OPENID",
          "msgtype":"text",
           "text":
          {
          "content":"THECONTENT"
          }
        }
        `
	//创建请求
	postReq, err := http.NewRequest("POST",
		"http://baidu.com", //post链接
		strings.NewReader(reqbody)) //post内容

	if err != nil {
		fmt.Println("POST请求:创建请求失败", err)
		return err
	}

	//增加header
	postReq.Header.Set("Content-Type", "application/json; encoding=utf-8")

	//执行请求
	client := &http.Client{}
	resp, err := client.Do(postReq)
	if err != nil {
		fmt.Println("POST请求:创建请求失败", err)
		return err
	} else {
		//读取响应
		body, err := ioutil.ReadAll(resp.Body) //此处可增加输入过滤
		if err != nil {
			fmt.Println("POST请求:读取body失败", err)
			return err
		}

		fmt.Println("POST请求:创建成功", string(body))
	}
	defer resp.Body.Close()

	return nil
}


func get() {
	response, _ := http.Get("http://127.0.0.1/")

	defer response.Body.Close()

	body, _ := ioutil.ReadAll(response.Body)

	fmt.Println(string(body))

	if response.StatusCode == 200 {
		fmt.Println("ok")
	} else {
		fmt.Println("error")
	}
}
func post() {
	resp, err := http.PostForm("http://127.0.0.1",
		url.Values{"name": {"ruifengyun"}, "blog": {"xiaorui.cc"},
			"aihao": {"python golang"}, "content": {"nima,fuck "}})

	fmt.Printf(resp, err)
}
